package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-book-mgr/cache"
	"red-book-mgr/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "不能为空",
		})
		return
	}
	book := model.Book{
		Title:   title,
		Content: content,
	}

	err := model.DB.Create(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "add_" + strconv.Itoa(int(book.ID))
	var data model.Book
	model.DB.Where("id=?", data.ID).Find(&data)
	jsonData, _ := json.Marshal(&data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Second*10)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
}
func Del(c *gin.Context) {
	id := c.Query("id")
	err := model.DB.Where("id=?", id).Delete(&model.Book{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "del_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
func List(c *gin.Context) {
	var data []model.Book
	redis_key := "list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Model(&model.Book{}).Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Second*5)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
}
